package com.flin.icesilkworm.examination.bas.service.impl;

import static org.apache.commons.lang3.StringUtils.isNotEmpty;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.flin.icesilkworm.examination.bas.constant.ITheExamineeTrainingConstant;
import com.flin.icesilkworm.examination.bas.constant.ITheQuestionBankConstant;
import com.flin.icesilkworm.examination.bas.model.TheExamineeTraining;
import com.flin.icesilkworm.examination.bas.model.TheQuestionItem;
import com.flin.icesilkworm.examination.bas.po.TheExamineeTrainingDo;
import com.flin.icesilkworm.examination.bas.po.TheQuestionBankDo;
import com.flin.icesilkworm.examination.bas.po.TheQuestionItemDo;
import com.flin.icesilkworm.examination.bas.service.ITheExamineeTrainingService;
import com.flin.icesilkworm.examination.gen.bas.po.GeneratedTheExamineeTrainingDo.TheExamineeTrainingAo;
import com.flin.icesilkworm.examination.gen.bas.service.GeneratedTheExamineeTrainingService;
import com.flin.icesilkworm.framework.jdbc.objects.CollectionUtils;
import com.flin.icesilkworm.framework.jdbc.pojo.JavaNameMap;
import com.flin.icesilkworm.framework.ui.pojo.ResultDto;
import com.flin.icesilkworm.framework.ui.pojo.UiViewForm;
@Service("theExamineeTrainingService")
@Transactional
public class TheExamineeTrainingServiceImpl extends GeneratedTheExamineeTrainingService implements ITheExamineeTrainingService,ITheExamineeTrainingConstant{

	@Transactional(readOnly=true)
	public ResultDto<JavaNameMap<?>> pageForMap(UiViewForm form) {
		
		ResultDto<JavaNameMap<?>> page = super.pageForMap(form);
		
		if(page.getTotal() > 0){
			Set<String> ids = new HashSet<>();
			for(JavaNameMap<?> map : page.getRows()){
				String bank = map.getString(ITheExamineeTrainingConstant.BANK_IDS);
				if(bank != null ){
					String [] banks = bank.split(",");
					for(String b : banks){
						ids.add(b.replace("[", "").replace("]", "").trim());
					}
				}
			}
		
			page.setExtendsMap(CollectionUtils.toMap("banks", TheQuestionBankDo.create()
					.where(t->t.andBankIdIn(ids.stream().map(Long::parseLong).collect(Collectors.toList()))
							.andDeletedEqualTo(Boolean.FALSE)
							.setAttribute(ITheQuestionBankConstant.BANK_ID,ITheQuestionBankConstant.QUES_BANK_NAME)
					).listForWhere()));  
		}
		
		
		return page;
		
		
	}
	
	public List<String> toList(String string,String s){
		
		String [] strs = string.split(s);
		List<String> list = new ArrayList<>();	
		Set<String> set = new HashSet<>();
		for(String str : strs){
			if(str.length() > 0){
				set.add(str.replace("[", "").replace("]", "").replace("\"", "").trim());
			}
		}
		
		list.addAll(set);//set.toArray(new String[0]));
		
		return list;
		
	}

	public List<TheQuestionItem> buildTraing(Long examTrainId) {
		
		TheExamineeTraining traing = findTheExamineeTrainingById(examTrainId);
		
		Integer num = traing.getSubCount();//题目数量

		if(num == null){num = 100;}
		
		int time =  (int)(System.currentTimeMillis() % 100);
		
		//次数
		TheExamineeTrainingDo.set().openRecord()
			.traingCount(traing.getTraingCount() != null ? traing.getTraingCount() + 1 : 1)
			.re().setExamTrainId(examTrainId).update();
		

		return  TheQuestionItemDo.create().where(t->t .andDeletedEqualTo(Boolean.FALSE) .orderBy("%{0}.ques_item_id * " + time + " % 33 ","desc"))
			.and(isNotEmpty(traing.getBankIds()), t->t.andQuesBankIdIn(toList(traing.getBankIds(),",").stream().map(Long::parseLong).collect(Collectors.toList())))
			//困难度
			.and(isNotEmpty(traing.getDefaultDifficultys()),t->t.andDefaultDifficultyIn(toList(traing.getDefaultDifficultys(),",")))
			//题型
			.and(isNotEmpty( traing.getQuesTypes()),t->t.andQuesTypeIn(toList(traing.getQuesTypes(),",")))
			.queryForWhere(0, num);
		
		
		
	}

	public List<TheQuestionItem> buildReinforcement(Long examTrainId) {
		
		TheExamineeTraining traing = findTheExamineeTrainingById(examTrainId);
		
		if(isNotEmpty(traing.getTheTitleRules())){
			
			return TheQuestionItemDo.create().where(t->t.andDeletedEqualTo(Boolean.FALSE)
					.andQuesItemIdIn(toList(traing.getTheTitleRules(),",").stream().map(Long::parseLong).collect(Collectors.toList())))
					.queryForWhere();
			
		}
		
		
		return null;
	}

	public boolean logTraingInfo(Long examTrainId, String finishInfo) {

		if(finishInfo != null){
			TheExamineeTrainingAo  ao = TheExamineeTrainingDo.set().openRecord();
			if(finishInfo.startsWith("e")){
				TheExamineeTraining traing = findTheExamineeTrainingById(examTrainId);
				String recordInfo = traing.getTheTitleRules();
				if(recordInfo == null) recordInfo = finishInfo.replace("e", "");
				else {
					if(recordInfo.length() > 900){
						recordInfo = recordInfo.substring(recordInfo.indexOf(",") + 1);
					}
					recordInfo = recordInfo + finishInfo.replace("e", ",");//放入队列
				}
				ao.theTitleRules(recordInfo);
			} else if(finishInfo.startsWith("f")){
				float f = Float.parseFloat(finishInfo.replace("f", ""));
				ao.finishedNumber((int)(f * 100));
			} else if(finishInfo.startsWith("s")){
				TheExamineeTraining traing = findTheExamineeTrainingById(examTrainId);
				String recordInfo = traing.getTheTitleRules();
				if(recordInfo != null && recordInfo.length() > 1){
					int sLen = recordInfo.length();
					recordInfo = (recordInfo + ",").replace(finishInfo.replace("s", "") + ",", "");
					if(sLen > recordInfo.length()){
						ao.theTitleRules(recordInfo);
					} else {
						return false;
					}
				} else {
					return false;
				}
			}
			ao.re().setExamTrainId(examTrainId).update();
			return true;
		}
		
		return false;
	}

}